package com.qf.mybatisplus.utils;

import org.apache.commons.codec.binary.Base64;
import sun.misc.BASE64Decoder;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;


public class Base64Util {
    public static String imageToBase64(String path) {
        byte[] data = null;
        try {
            InputStream in = new FileInputStream(path);
            data = new byte[in.available()];
            in.read(data);
            in.close();
        } catch (IOException e) {
            e.printStackTrace();

        }
        Base64 base64 = new Base64();
        return base64.encodeToString(data);
    }

    public static boolean base64ToImage(String base64Str, String path) {
        if (base64Str == null) {
            return false;
        }
        Base64 base64 = new Base64();
        try {
            byte[] bytes = Base64.decodeBase64(base64Str);
            for (int i = 0; i < bytes.length; ++i) {
                if (bytes[i] < 0) {
                    bytes[i] += 256;
                }
            }
            File img = new File(path);
            if (!img.getParentFile().exists()) {
                img.getParentFile().mkdirs();
            }
            OutputStream out = new FileOutputStream(path);
            out.write(bytes);
            out.flush();
            out.close();
            return true;
        } catch (Exception e) {
            return false;
        }
    }

    /**
     　　* @Description: url路径转换为base64
     　　* @throws
     　　* @author MR.Zhang
     　　* @date 2019-6-28 16:32
     　　*/
    public static String getImgStr(String urlStr){
        ByteArrayOutputStream data = new ByteArrayOutputStream();
        try {
            // 创建URL
            urlStr = urlEncode(urlStr);//url编码
            URL url = new URL(urlStr);
            byte[] by = new byte[1024];
            // 创建链接
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("GET");
            conn.setConnectTimeout(5000);
            InputStream is = conn.getInputStream();
            // 将内容放到内存中
            int len = -1;
            while ((len = is.read(by)) != -1) {
                data.write(by, 0, len);
            }
            is.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        // 对字节数组Base64编码
        Base64 base64 = new Base64();
        return base64.encodeToString(data.toByteArray());
    }

    /**
     * url编码
     * @param urlStr
     * @return
     * @throws UnsupportedEncodingException
     */
    public static String urlEncode(String urlStr) throws UnsupportedEncodingException {
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < urlStr.length(); i++) {
            char c = urlStr.charAt(i);
            //如果是中文进行url编码
            if (String.valueOf(c).matches("[\u4e00-\u9fa5]")){
                sb.append(URLEncoder.encode(String.valueOf(c),"utf-8"));
            }else {
                sb.append(String.valueOf(c));
            }
        }
        return sb.toString();
    }

    /**
     * base64转二级制流
     * @param base64String
     * @return
     */
    public static byte[] base64ToByte(String base64String){
        BASE64Decoder decoder = new BASE64Decoder();
        try {
            return base64String != null ? decoder.decodeBuffer(base64String) : null;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }


    public static void main(String[] args) {
        String base64Info = "iVBORw0KGgoAAAANSUhEUgAAAPoAAAD6AQAAAACgl2eQAAABYElEQVR42u2YUY7EIAxDI3EAjtSrcyQOUCkb2+1InUX7Xa9ATKct7ycKMU4j/x4jNrCBDWzAHjgDo65tHjmPsw88dzcA96N+0UetNt6ffsCopQqwzRBQIbsCWUuZM9wBbrwDKbMEuOUqWXfRr/fkywGVP6tGc60P7wY0Kk2YANZa/XJA2+wjwmf/nSwDoP7rkQoMBQgG29INqNMwFWZSjVORugGVoqv2G0Ug+jNZDgDNCSazNnhjCHQFiDTJcbGUzADlSxPJgmmM0w2ooJQylgxMY8vhB/RkXNDh5ylvBTDAelnRoYKgxtH8gOMyJ3hf1hHwVzY9AEjxkA6L/LIoFgCPdQIzNJobcNtF9eawuxIEL0DWXTocFDFL4G6jyqjIblGQ7YCh0Gi3rh7qsSedgPj4xjYXnbsFoFV2H+tkvR5gJ0Xh4ntGbQdcnxdSzSAOl7nQh5cD+6v7BjawgX8L/ACf6JLSrquCEQAAAABJRU5ErkJggg==";
        String diskPath = "D:/moko/nginx-1.20.1/html/MOKO-IMG/code/QrCode.jpg";

        Base64Util.base64ToImage(base64Info,diskPath);
    }
}
